import React, { Component } from 'react'
import ReactDOM from 'react-dom'

import styles from './index.less'

const menuWidth = 130;
const listHeight = 28;

export default class ContextMenu extends Component {

    state = {
        offsetTop: 64,
        visible: false,
        x: 0,
        y: 0
    }
    componentDidMount = () => {
        document.addEventListener('contextmenu', this._contextMenu)
        document.addEventListener('click', this._hideMenu)
        document.addEventListener('keyup', this._escKey)
    }

    componentWillMount = () => {
        document.removeEventListener('contextmenu', this._contextMenu)
        document.removeEventListener('click', this._hideMenu)
        document.removeEventListener('keyup', this._escKey)
    }

    _contextMenu = (e) => {
        e.stopPropagation();
        let clientW = document.body.clientWidth;
        let clientH = document.body.clientHeight;
        let menuHeight = listHeight * this.props.menu.length

        let x = e.pageX + menuWidth > clientW ? e.pageX - menuWidth : e.pageX
        let y = e.pageY + menuHeight > clientH ? e.pageY - menuHeight : e.pageY

        this.setState({
            visible: true,
            x,
            y
        });

        e.cancelBubble = true
        e.returnValue = false;
        return false;
    }

    _hideMenu = (e) => {
        this.setState({
            visible: false
        });
    }
    _escKey = (e) => {
        if (e.which === 27) {
            this.setState({
                visible: false
            });
        }
    }

    menuItem = () => {

    }


    render() {
        this.node = document.createElement('div');
        const { visible, x, y, offsetTop } = this.state;
        const { menu } = this.props;
        const tmpStyle = {
            display: visible ? 'block' : 'none',
            width: `${menuWidth}px`,
            left: `${x}px`,
            top: `${y - offsetTop}px`,
        };
        const menuNode = (
            <div className={styles.contextMenu} style={tmpStyle}>
                <ul>
                    {
                        menu.map((item, index) => {
                            return <li key={index}><a style={{ height: `${listHeight}px`, lineHeight: `${listHeight}px` }}>{item.title}</a></li>
                        })
                    }
                </ul>
            </div>
        )
        ReactDOM.render(menuNode, this.node);
        document.body.appendChild(this.node);
        return null;
    }
}
